﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using BookList.BooklistManagement.Books.Dto;

namespace BookList.BooklistManagement.Books
{
    public class BookAppService : BookListAppServiceBase, IBookAppService
    {
        private readonly IRepository<Books, long> _bookRepository;

        public BookAppService(IRepository<Books, long> bookRepository)
        {
            _bookRepository = bookRepository;
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task BatchDeleteBook(List<long> input)
        {
            await _bookRepository.DeleteAsync(a => input.Contains(a.Id));
        }

        public  async Task CreateOrUpdateBook(CreateOrUpdateBookInput input)
        {
            //判断是否有ID,
            if (input.Book.Id.HasValue)
            {
                //有Id修改
                await UpdateBook(input.Book);
            }
            else
            {
                //没有Id创建
                await CreateBook(input.Book);
            }
        }
        /// <summary>
        /// 修改书籍
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        protected virtual async Task UpdateBook(BookEditDto input)
        {
            Debug.Assert(input.Id!=null, "input.Id!=null");
            var entity = await _bookRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);
            await _bookRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 创建书籍
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        protected virtual async  Task<BookEditDto> CreateBook(BookEditDto input)
        {

            var entity = input.MapTo<Books>();
            await _bookRepository.InsertAsync(entity);
            return entity.MapTo<BookEditDto>();
           
        }
        /// <summary>
        /// 获取编辑状态下的实体
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<GetBookForEditOutput> GetBookForEditBookAsync(NullableIdDto<long> input)
        {
            var output=new GetBookForEditOutput();
            BookEditDto editDto;
            if (input.Id.HasValue)
            {
                var entity = await _bookRepository.GetAsync(input.Id.Value);
                editDto = entity.MapTo<BookEditDto>();

            }
            else
            {
                editDto=new BookEditDto();
            }

            output.Book = editDto;
            return output;
        }

        public Task<PagedResultDto<BooklistDto>> GetPageBook(GetBookInput input)
        {
            throw new System.NotImplementedException();
        }
    }
}